/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.anhndt.audiobook.ui;

import com.anhndt.audiobook.business.Resource;
import com.anhndt.audiobook.ui.renderer.ItemRendererImpl;
import com.anhndt.audiobook.entity.ItemEntity;
import com.anhndt.audiobook.iface.ProcessListener;
import com.anhndt.audiobook.parser.ItemParser;
import com.anhndt.audiobook.utils.Util;
import com.sun.lwuit.Command;
import com.sun.lwuit.Display;
import com.sun.lwuit.List;
import com.sun.lwuit.events.ActionEvent;
import com.sun.lwuit.layouts.BorderLayout;
import com.sun.lwuit.list.DefaultListModel;
import java.util.Vector;

/**
 *
 * @author Sun
 */
public class CategoryForm extends BaseForm {

    private ItemEntity selectedItem;
    private int lastIndexSelected;
    List listArticle;

    public CategoryForm(String title, BaseForm previous, ItemEntity parentEntity) {
        this(TAG_UNKNOWN, title, previous, parentEntity);
    }

    public CategoryForm(byte tag, String title, BaseForm previous, ItemEntity parentEntity) {
        super(tag, title, previous, parentEntity);
        setSupportSearch(true);
    }

    public void show() {
        super.show();
        if (listArticle != null && listItem != null) {
            listItem.getComponentForm().setFocused(listItem);
            listArticle.getRenderer().getListCellRendererComponent(listArticle, listArticle.getSelectedItem(), listArticle.getSelectedIndex(), false).getSelectedStyle().setBgTransparency(Resource.TRANSPARENCE);
        }
    }

    protected void releaseAll() {
        super.releaseAll();
        listArticle = null;
    }

    protected void init() {
        Display.getInstance().setThirdSoftButton(false);
        super.init();
        ItemEntity curItemEntity = (selectedItem == null || !selectedItem.hasParentEntity()) ? parentEntity : selectedItem.getParent();
        Vector articles = curItemEntity.getValue("" + ItemEntity.TYPE_ARTICLE);
        bindListArticle(articles);
        //TODO invisible load thumb for articles
        loadThumb(articles);
        if (curItemEntity != null && parentEntity.size() > 0) {
            Vector categories = curItemEntity.getItemChildrends("" + ItemEntity.TYPE_CATEGORY);
            changeListModel(categories, lastIndexSelected);
        }
        form.addCommand(cmdView);
    }

    private void bindListArticle(Vector articles) {
        if (articles == null || articles.size() == 0) {
            listArticle = null;
            return;
        }
        if (listArticle == null) {
            listArticle = new ListItem(articles);
            listArticle.setOrientation(List.HORIZONTAL);
            listArticle.setFixedSelection(List.FIXED_NONE_CYCLIC);
            listArticle.setListCellRenderer(new ItemRendererImpl());
            listArticle.addActionListener(this);
            body.addComponent(BorderLayout.NORTH, listArticle);
        } else {
            listArticle.setModel(new DefaultListModel(articles));
        }
    }

    /**
     * Ham nay duoc goi khi nguoi dung click vao CommandBack
     */
    protected void backScreen() {
        if (listItem == null || listItem.size() == 0) {
            super.backScreen();
            return;
        }
        ItemEntity curItemEntity = (ItemEntity) listItem.getSelectedItem();
        if (curItemEntity.hasParentEntity()) {
            ItemEntity parentItemEnttity = curItemEntity.getParent();
            if (parentItemEnttity.hasParentEntity()) {
                ItemEntity grandItemEntity = parentItemEnttity.getParent();
                int index = grandItemEntity.indexOf(parentItemEnttity, "" + ItemEntity.TYPE_CATEGORY);
                changeListModel(grandItemEntity.getItemChildrends("" + ItemEntity.TYPE_CATEGORY), index);
                form.setFocused(listItem);
            } else {
                super.backScreen();
            }
        } else {
            super.backScreen();
        }
    }

    protected void itemSelected(int index) {
        listItem.setHandlesInput(true);
        lastIndexSelected = index;
        selectedItem = getCurrentItemEntity();
        ProcessListener callback = new ProcessListener() {

            public void onSuccess(Object result, int index) {
                if (selectedItem.counterChild <= 0) {
                    // changeListModel
                    bindListArticle(selectedItem.getItemChildrends("" + ItemEntity.TYPE_ARTICLE));
                    changeListModel(selectedItem.getItemChildrends("" + ItemEntity.TYPE_CATEGORY), 0);
                } else {
                    //show ArticleForm
                    boolean hasArticle = selectedItem.containtType("" + ItemEntity.TYPE_ARTICLE);
                    if (hasArticle) {
                        formChild = new ArticleForm(selectedItem.name, CategoryForm.this, selectedItem);
                        showFormChild(formChild);
                    }
                }
            }

            public void onError(String status, int index) {
            }
        };
        ItemParser parserArticle = new ItemParser(selectedItem, null, "" + Util.displayCounter, "" + 1, false);
        getResponseItem(selectedItem, parserArticle, callback);
    }

    private void itemArticleSeleted() {
        //TODO action article
        final ItemEntity articleItemSelected = (ItemEntity) listArticle.getSelectedItem();
        Util.lastArticleID = articleItemSelected.id;
        ProcessListener callback = new ProcessListener() {

            public void onSuccess(Object result, int index) {
//                Vector vtAdvText = (Vector) articleItemSelected.getItemChildrends("" + ItemEntity.TYPE_ADVERTISE_TEXT);
//                String advText = vtAdvText.size() > 0 ? vtAdvText.elementAt(0).toString() : title;
                formChild = new ArticlePartForm(articleItemSelected.name, CategoryForm.this, articleItemSelected, articleItemSelected);
                showFormChild(formChild);
            }

            public void onError(String status, int index) {
            }
        };
        ItemParser parserArticlePart = new ItemParser(articleItemSelected, null, "" + Util.displayCounter, "" + 1, false);
        getResponseItem(articleItemSelected, parserArticlePart, callback);
    }

    public void actionPerformed(ActionEvent evt) {
        Command cmd = evt.getCommand();
        if (cmd == cmdView) {
            if (form.getFocused() == listItem) {
                itemSelected(listItem.getSelectedIndex());
            } else if (form.getFocused() == listArticle) {
                itemArticleSeleted();
            }
        } else if (evt.getSource() == listItem) {
            itemSelected(listItem.getSelectedIndex());
        } else if (evt.getSource() == listArticle) {
            itemArticleSeleted();
        }
    }

    private ItemEntity getCurrentItemEntity() {
        ItemEntity curItemEntity;
        if (listItem == null || listItem.size() == 0) {
            curItemEntity = parentEntity;
        } else {
            curItemEntity = (ItemEntity) listItem.getSelectedItem();
        }
        return curItemEntity;
    }
}
